package com.znsd.zl.order.service.impl;

import com.znsd.zl.order.dao.IOrderDao;
import com.znsd.zl.order.entity.OrderEntity;
import com.znsd.zl.order.entity.vo.OrderEntityVo;
import com.znsd.zl.order.service.IOrderService;
import com.znsd.zl.order.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @ClassName DelayedService
 * @Description InitializingBean 是bean 生命周期的一个接口，用来初始化自定义数据
 * @Author zhubin
 * @Date 2020/8/31 15:08
 * @Version v1.0
 */
@Service
@Slf4j
public class DelayedService implements InitializingBean {

	private static DelayQueue<OrderEntity> delayQueue = new DelayQueue<>();
	private static AtomicBoolean start = new AtomicBoolean(false);
	@Resource
	private TaskExecutor taskExecutor;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private RedisUtils redisUtils;
	@Resource
	IOrderDao orderDao;
	/**
	 * 在类初始化的时候启用 start方法
	 * @throws Exception
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		start();
	}

	/**
	 * 启动延迟队列，执行延迟任务
	 */
	public void start(){
		if (start.get()) {
			return;
		}
		start.set(true);
		// 启动DelayQueue
		taskExecutor.execute(() -> {
			while (true) {
				// 使用等待方式获取队列数据
				try {
					OrderEntity orderEntity = delayQueue.take();
					if (orderEntity != null) {
						log.info("expired object ======>"+orderEntity);
						// 修改订单状态
						orderService.setStatusCancel(orderEntity.getId());
						try {
							redisUtils.del(String.valueOf(orderEntity.getRentId()));
						}catch (Exception e){
							log.error("redis 操作失败，请手动删除key==={}", orderEntity.getRentId());
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 添加延迟任务
	 * @param orderEntity  保存的数据
	 * @return  true成功 false 失败
	 */
	public boolean add(OrderEntity orderEntity){
		if (orderEntity != null) {
			delayQueue.add(orderEntity);
			return true;
		}
		return false;
	}

	/**
	 * 更改订单 状态
	 * @param orderId       修改id
	 * @param updateStatus  1 表示成功状态   3 表示取消
	 */
	public void update(Integer orderId,Integer updateStatus){
		Iterator<OrderEntity> orders = delayQueue.iterator();
		OrderEntity orderEntity = null;
		while (orders.hasNext()) {
			OrderEntity order = orders.next();
			if (orderId.equals(order.getId())) {
				orderEntity = order;
				if (updateStatus == 1) {
					orderService.setStatusSuccess(orderEntity.getId());
					// 给房东添加余额
					OrderEntityVo orderEntityVo = (OrderEntityVo) orderEntity;
					try {
						orderDao.userPayment(orderEntityVo.getLandlordUserId(), orderEntity.getPayment());
					} catch (Exception e) {
						log.error("给房东付款失败 房东编号==》{}  付款金额==》{}   付款用户===》{}",
								orderEntityVo.getLandlordUserId(),orderEntity.getPayment(), orderEntity.getUserId());
					}
				} else {
					// 修改状态已取消
					orderService.setStatusCancel(orderEntity.getId());
				}
				try {
					redisUtils.del(String.valueOf(orderEntity.getRentId()));
				}catch (Exception e){
					log.error("redis 操作失败，请手动删除key==={}", orderEntity.getRentId());
				}
				break;
			}
		}
		delayQueue.remove(orderEntity);
	}

	/**
	 * 校验 订单id 是否在延迟队列中存在
	 * @param orderId
	 * @return    true 找到，false 没找到
	 */
	public boolean checkOrderId(Integer orderId){
		Iterator<OrderEntity> iterator = delayQueue.iterator();
		while (iterator.hasNext()) {
			OrderEntity orderEntity = iterator.next();
			if (orderId.equals(orderEntity.getId())) {
				return true;
			}
		}
		return false;
	}
}
